<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>京东价格查询</title>
    <script src="jsonp.js"></script>
</head>
<style>
    body{
        margin:0;
        padding: 50px;
    }
    #sku{
        width: 100%;
        padding:20px;
        box-sizing: border-box;
        font-size: 20px;
    }
</style>
<body>
    <!--<input type="file" id="file" accept=".csv">
    <button onclick="readFile()">读取</button>-->
    <input type="text" id="sku" placeholder="请输入京东编码按回车键结束">
    <p>京东价格为:<span id="price">0</span></p>
</body>
<script>
    var input = document.querySelector('#sku');
    var price = document.querySelector('#price');
    var file = document.querySelector('#file')
    input.addEventListener('keyup',function(e){
        if(e.keyCode===13||e.code =='Enter'){
            price.innerText = '请稍等...'
            var code = document.querySelector('#sku').value;
            var url='https://p.3.cn/prices/mgets?skuIds='+code;
            jsonp(url,function(err,res){
                if(err){
                    price.innerText = '查询错误！'
                }else{
                    price.innerText = res[0].p;
                    input.value = ''
                }
            });
            setTimeout(function(){
                if(price.innerText == '请稍等...'){
                    price.innerText = '超时...'
                };
            },3000)
        }
    })
    function readFile(){
        var cfile = file.files[0];
        var reader =   new FileReader();
        reader.readAsText(cfile,'gb2312');
        reader.onload = function(){
            csv2json(reader.result)
        }
    };
    function csv2json(res){
        var resArr = res.split(/\n/);
        var titles = resArr[0];
        resArr.splice(0,1);
        var title = titles.split(',');
        console.log(title);
        var result = [];
        for(let i = 0;i<resArr.length;i++){
            let cacheObj = {};
            let val = resArr[i].split(',');
            for(let j = 0;j<title.length;j++){
                let val1 = val[j];
                //val1.replace(/\"/g,'');
                if(val1){
                    val1 = val1.replace(/\"|\s/g,'');
                    cacheObj[title[j]] = val1;
                }else{
                    cacheObj[title[j]] = val1;
                }
                
            }
            if(Object.values(cacheObj)[0]){
                result.push(cacheObj);
            }
        }
        window.results = result;
    }
</script>
</html>